import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:multi_shop/utils/index.dart';
import 'package:pinput/pinput.dart';

enum PasswordMode { pay, login }

extension _ModeExt on PasswordMode {
  String get title => this == PasswordMode.pay ? '修改支付密码' : '修改登录密码';
  String get oldLabel => this == PasswordMode.pay ? '原支付密码' : '原登录密码';
  String get newLabel => this == PasswordMode.pay ? '新支付密码' : '新登录密码';
  String get confirmLabel => this == PasswordMode.pay ? '确认新支付密码' : '确认新登录密码';
}

class ChangePasswordDialog extends StatefulWidget {
  /// 模式：支付密码 / 登录密码
  final PasswordMode mode;

  /// PIN 长度；支付密码一般 6 位，登录密码如用 Pinput 也建议固定长度（默认同 6）
  final int pinLength;

  /// 是否需要输入旧密码
  final bool requireOld;

  /// 点击确认时回调（抛异常或返回 Future 报错即视为失败）
  final Future<void> Function({required String oldPwd, required String newPwd})
  onConfirm;
  const ChangePasswordDialog({
    Key? key,
    required this.mode,
    required this.onConfirm,
    this.pinLength = 6,
    this.requireOld = true,
  }) : super(key: key);

  @override
  State<ChangePasswordDialog> createState() => _ChangePasswordDialogState();

  /// 便捷调用
  static Future<bool?> show(
    BuildContext context, {
    required PasswordMode mode,
    required Future<void> Function({
      required String oldPwd,
      required String newPwd,
    })
    onConfirm,
    int pinLength = 6,
    bool requireOld = true,
  }) {
    return Get.dialog<bool>(
      ChangePasswordDialog(
        mode: mode,
        onConfirm: onConfirm,
        pinLength: pinLength,
        requireOld: requireOld,
      ),
      barrierDismissible: false,
    );
  }
}

class _ChangePasswordDialogState extends State<ChangePasswordDialog> {
  final _oldCtrl = TextEditingController();
  final _newCtrl = TextEditingController();
  final _confirmCtrl = TextEditingController();

  bool _obscureText = true;
  bool _loading = false;

  void _togglePassword() {
    setState(() {
      _obscureText = !_obscureText;
    });
  }

  PinTheme _pinBaseTheme(BuildContext context) {
    return PinTheme(
      width: 44,
      height: 48,
      textStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.black12),
        color: Colors.white,
      ),
    );
  }

  PinTheme _pinFocusedTheme(BuildContext context) {
    final base = _pinBaseTheme(context);
    return base.copyWith(
      decoration: base.decoration?.copyWith(
        border: Border.all(
          color: Theme.of(context).colorScheme.primary,
          width: 2,
        ),
      ),
    );
  }

  PinTheme _pinErrorTheme(BuildContext context) {
    final base = _pinBaseTheme(context);
    return base.copyWith(
      decoration: base.decoration?.copyWith(
        border: Border.all(color: Colors.red, width: 2),
      ),
    );
  }

  List<TextInputFormatter> _formatters() {
    // 支付密码：纯数字
    if (widget.mode == PasswordMode.pay) {
      return [FilteringTextInputFormatter.digitsOnly];
    }
    // 登录密码：允许任意字符（如果你要限制只能字母数字，可以换成对应的正则）
    return [];
  }

  TextInputType _keyboardType() {
    return widget.mode == PasswordMode.pay
        ? TextInputType.number
        : TextInputType.visiblePassword;
  }

  String? _validateAll() {
    final len = widget.pinLength;

    if (widget.mode == PasswordMode.pay) {
      if (widget.requireOld && _oldCtrl.text.length != len) {
        return '请输入${len}位${widget.mode == PasswordMode.pay ? "原支付密码" : "原登录密码"}';
      }
      if (_newCtrl.text.length != len) {
        return '请输入${len}位${widget.mode == PasswordMode.pay ? "新支付密码" : "新登录密码"}';
      }
    } else {
      if (widget.requireOld && _oldCtrl.text.length < len) {
        return '请输入至少${len}位${widget.mode == PasswordMode.pay ? "原支付密码" : "原登录密码"}';
      }
      if (_newCtrl.text.length < len) {
        return '请输入至少${len}位${widget.mode == PasswordMode.pay ? "新支付密码" : "新登录密码"}';
      }
    }

    if (_confirmCtrl.text != _newCtrl.text) {
      return '两次输入不一致';
    }
    // // 登录密码可选：简单复杂度校验（示例）
    // if (widget.mode == PasswordMode.login) {
    //   final v = _newCtrl.text;
    //   // 例如至少含数字和字母（你也可以去掉这段）
    //   final hasDigit = v.contains(RegExp(r'\d'));
    //   final hasLetter = v.contains(RegExp(r'[A-Za-z]'));
    //   if (!(hasDigit && hasLetter)) {
    //     return '登录密码需包含字母和数字';
    //   }
    // }
    return null;
  }

  Future<void> _submit() async {
    final err = _validateAll();
    if (err != null) {
      AppToast.show(err);
      // Get.snackbar('提示', err, snackPosition: SnackPosition.TOP);
      return;
    }
    try {
      setState(() => _loading = true);
      await widget.onConfirm(oldPwd: _oldCtrl.text, newPwd: _newCtrl.text);
      setState(() => _loading = false);
      Get.back(result: true);
      Get.snackbar('成功', '密码已更新', snackPosition: SnackPosition.TOP);
    } catch (e) {
      setState(() => _loading = false);
      AppToast.show(e.toString());
      // Get.snackbar('失败', e.toString(), snackPosition: SnackPosition.TOP);
    }
  }

  @override
  void dispose() {
    _oldCtrl.dispose();
    _newCtrl.dispose();
    _confirmCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final len = widget.pinLength;
    final labelStyle = TextStyle(fontSize: 14, color: Colors.grey[700]);

    return AlertDialog(
      title: Text(widget.mode.title),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (widget.requireOld) ...[
              Align(
                alignment: Alignment.centerLeft,
                child: Text(widget.mode.oldLabel, style: labelStyle),
              ),
              const SizedBox(height: 6),
              widget.mode == PasswordMode.pay
                  ? Pinput(
                      length: len,
                      controller: _oldCtrl,
                      obscureText: true,
                      obscuringCharacter: '●',
                      inputFormatters: _formatters(),
                      keyboardType: _keyboardType(),
                      autofocus: true,
                      defaultPinTheme: _pinBaseTheme(context),
                      focusedPinTheme: _pinFocusedTheme(context),
                      errorPinTheme: _pinErrorTheme(context),
                    )
                  : TextFormField(
                      controller: _oldCtrl,
                      obscureText: _obscureText,
                      decoration: InputDecoration(
                        labelText: '密码',
                        prefixIcon: Icon(Icons.lock),
                        suffixIcon: IconButton(
                          icon: Icon(
                            _obscureText
                                ? Icons.visibility
                                : Icons.visibility_off,
                          ),
                          onPressed: _togglePassword,
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入密码';
                        }
                        if (value.length < 6) {
                          return '密码不能少于6位';
                        }
                        return null;
                      },
                    ),
              const SizedBox(height: 16),
            ],
            Align(
              alignment: Alignment.centerLeft,
              child: Text(widget.mode.newLabel, style: labelStyle),
            ),
            const SizedBox(height: 6),
            widget.mode == PasswordMode.pay
                ? Pinput(
                    length: len,
                    controller: _newCtrl,
                    obscureText: true,
                    obscuringCharacter: '●',
                    inputFormatters: _formatters(),
                    keyboardType: _keyboardType(),
                    defaultPinTheme: _pinBaseTheme(context),
                    focusedPinTheme: _pinFocusedTheme(context),
                    errorPinTheme: _pinErrorTheme(context),
                  )
                : TextFormField(
                    controller: _newCtrl,
                    obscureText: _obscureText,
                    decoration: InputDecoration(
                      labelText: '密码',
                      prefixIcon: Icon(Icons.lock),
                      suffixIcon: IconButton(
                        icon: Icon(
                          _obscureText
                              ? Icons.visibility
                              : Icons.visibility_off,
                        ),
                        onPressed: _togglePassword,
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入密码';
                      }
                      if (value.length < 6) {
                        return '密码不能少于6位';
                      }
                      return null;
                    },
                  ),
            const SizedBox(height: 16),
            Align(
              alignment: Alignment.centerLeft,
              child: Text(widget.mode.confirmLabel, style: labelStyle),
            ),
            const SizedBox(height: 6),
            widget.mode == PasswordMode.pay
                ? Pinput(
                    length: len,
                    controller: _confirmCtrl,
                    obscureText: true,
                    obscuringCharacter: '●',
                    inputFormatters: _formatters(),
                    keyboardType: _keyboardType(),
                    defaultPinTheme: _pinBaseTheme(context),
                    focusedPinTheme: _pinFocusedTheme(context),
                    errorPinTheme: _pinErrorTheme(context),
                  )
                : TextFormField(
                    controller: _confirmCtrl,
                    obscureText: _obscureText,
                    decoration: InputDecoration(
                      labelText: '密码',
                      prefixIcon: Icon(Icons.lock),
                      suffixIcon: IconButton(
                        icon: Icon(
                          _obscureText
                              ? Icons.visibility
                              : Icons.visibility_off,
                        ),
                        onPressed: _togglePassword,
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入密码';
                      }
                      if (value.length < 6) {
                        return '密码不能少于6位';
                      }
                      return null;
                    },
                  ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: _loading ? null : () => Get.back(),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: _loading ? null : _submit,
          child: _loading
              ? const SizedBox(
                  width: 18,
                  height: 18,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : const Text('确定'),
        ),
      ],
    );
  }
}
